package com.booksystem.exception;

import com.booksystem.common.BusinessException;
import com.booksystem.common.RestResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * <p>
 *   全局异常处理器
 * </p>
 * @author 段伟豪
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionAdvice {

    /**
     * 处理业务异常
     *
     * @param exception 业务异常
     * @return ResponseEntity
     */
    @ExceptionHandler(BusinessException.class)
    public ResponseEntity<RestResult<Object>> handleBusinessException(BusinessException exception) {
        log.error(exception.getMessage(), exception);
        return new ResponseEntity<>(new RestResult<>(exception.getCode(), exception.getMsg()), HttpStatus.OK);
    }

    /**
     * 处理未知异常
     *
     * @param throwable 异常对象
     * @return ResponseEntity
     */
    @ExceptionHandler(Throwable.class)
    public ResponseEntity<RestResult<String>> handleException(Throwable throwable) {
        log.error(throwable.getMessage(), throwable);
        return new ResponseEntity<>(new RestResult<>("SERVER_ERROR", "服务器内部错误"), HttpStatus.INTERNAL_SERVER_ERROR);
    }

    /**
     * 处理HTTP方法不支持异常
     *
     * @param exception 不支持的方法异常
     * @return ResponseEntity
     */
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public ResponseEntity<RestResult<String>> handleHttpRequestMethodNotSupportedException(
            HttpRequestMethodNotSupportedException exception) {
        log.error("请求方法不支持: ", exception);
        return new ResponseEntity<>(new RestResult<>("METHOD_NOT_ALLOWED", "请求方法不支持"), HttpStatus.METHOD_NOT_ALLOWED);
    }
}